import os

from cvsanaly_fork import generations
from db.mydatabase import MyDatabase
from settings import *

OUTPUT_MASTER_DIR = os.path.join(OUTPUT_DIR,'svn/')

class GenerationsScript:

    def __init__ (self, user = None, password = None, proj_db_filename = None, output_dir = None):

        self.output_dir = output_dir

        self.user = user
        self.password = password
        
        self.proj_db_filename = proj_db_filename
        self.proj_db = {}
        
    def readProjects(self):

        proj_db_file = open(self.proj_db_filename)

        for l in proj_db_file.readlines():
            proj, dbname = l.rstrip('\n').split('\t')
            self.proj_db[proj] = dbname

        proj_db_file.close()
        
    def run (self):

        self.readProjects()

        for proj in self.proj_db.keys():

            # Ignore commented lines
            if "#" in proj:
                continue

            dbname = self.proj_db[proj]
            
            self.db = MyDatabase()
            self.db.user = self.user
            self.db.password = self.password
            self.db.name = dbname

            self.db.connect()

            
            gens_directory = os.path.join(self.output_dir,proj)
            if not os.path.isdir (gens_directory):
                os.makedirs (gens_directory)

            #try:
            if 1:
                #period = generations.periodSlots(10)
                #gen = generations.generations (self.db, gens_directory, period)

                period = generations.periodSlots(20)
                gen = generations.generations (self.db, gens_directory, period)

                #period = generations.periodDays(300)
                #gen = generations.generations (self.db, gens_directory, period)
                #period = generations.periodDays(200)
                #gen = generations.generations (self.db, gens_directory, period)
                #period = generations.periodQuarter()
                #gen = generations.generations (self.db, gens_directory, period)
            #except:
            #    print "**** ERROR with project "+proj
            #    continue

if '__main__' == __name__:

    gs = GenerationsScript(mysql_user,mysql_password,"projects",OUTPUT_MASTER_DIR)
    gs.run()
